package com.zt.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zt.aliyun.RealnameAuthentication;
import com.zt.pojo.TeacherCertification;
import com.zt.pojo.Teachers;
import com.zt.pojo.Subjects;
import com.zt.pojo.Order;
import com.zt.pojo.Courses;
import com.zt.pojo.Bookings;
import com.zt.pojo.Users;
import com.zt.pojo.TeacherRating;
import com.zt.dto.TeacherRatingRequest;
import com.zt.service.TeacherCertificationService;

import com.zt.service.TeachersService;
import com.zt.service.SubjectsService;
import com.zt.service.OrdersService;
import com.zt.service.CoursesService;
import com.zt.service.BookingsService;
import com.zt.service.TeacherRatingService;
import com.zt.service.TeacherAvailableService;
import com.zt.entity.Result;
import com.zt.service.UsersService;
import com.zt.dto.TeacherAvailableRequest;
import com.zt.dto.CourseAssignmentRequest;
import com.zt.pojo.TeacherAvailable;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.math.BigDecimal;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@RestController
public class TeacherController {

    @Autowired
    private TeachersService teachersService;

    @Autowired
    private SubjectsService subjectsService;

    @Autowired
    private TeacherCertificationService teacherCertificationService;

    @Autowired
    private TeacherRatingService teacherRatingService;


    @Autowired
    private UsersService usersService;

    @Autowired
    private OrdersService ordersService;

    @Autowired
    private CoursesService coursesService;

    @Autowired
    private BookingsService bookingsService;

    @Autowired
    private TeacherAvailableService teacherAvailableService;

    private static final String APPCODE="66c930a87c3d48bcb527527dac76503e";

    /**
     * 解析Integer参数，处理"null"字符串和空值
     * @param param 参数字符串
     * @return Integer值或null
     */
    private Integer parseIntegerParam(String param) {
        if (param == null || param.trim().isEmpty() || "null".equalsIgnoreCase(param.trim())) {
            return null;
        }
        try {
            return Integer.parseInt(param.trim());
        } catch (NumberFormatException e) {
            return null;
        }
    }

    /**
     * 获取教师列表（兼容旧版接口）
     * @param subject 科目
     * @param keyword 关键词（用于搜索教师名称）
     * @param page 页码
     * @param size 每页大小
     * @return 教师列表
     */
    @GetMapping({"/teachers", "/user/teachers", "/teachers/list", "/user/teachers/list"})
    public Result getTeacherList(
            @RequestParam(value = "subject", required = false) String subject,
            @RequestParam(value = "keyword", required = false) String keyword,
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "size", defaultValue = "10") Integer size) {

        System.out.println("======= 获取教师列表 =======");
        System.out.println("请求参数: subject=[" + subject + "], keyword=[" + keyword + "], page=" + page + ", size=" + size);

        // 检查请求头信息
        System.out.println("请求头信息: " +
            org.springframework.web.context.request.RequestContextHolder.currentRequestAttributes()
                .getAttribute("org.springframework.web.servlet.HandlerMapping.bestMatchingPattern",
                    org.springframework.web.context.request.RequestAttributes.SCOPE_REQUEST));

        // 如果科目为空或为"全部"，则不过滤科目
        if (subject == null || "全部".equals(subject) || subject.isEmpty()) {
            System.out.println("科目参数为空或为'全部'，不进行科目过滤");
            return searchTeachers(page, size, keyword, null, null, null, 1,null);
                } else {
            System.out.println("按科目过滤: " + subject);
            return searchTeachers(page, size, keyword, subject, null, null, 1,null);
        }
    }

    /**
     * 获取教师详情
     * @param id 教师ID
     * @return 教师详情
     */
    @GetMapping({"/teachers/detail", "/teacher/detail", "/user/teacher/detail"})
    public Result getTeacherDetail(@RequestParam(value = "id", required = true) Integer id) {
        System.out.println("获取教师详情，ID: " + id);

        try {
            // 查询教师信息
            Teachers teacher = teachersService.getById(id);
            if (teacher == null) {
                return Result.error("教师不存在");
            }

            // 查询所有科目
            List<Subjects> allSubjects = subjectsService.list();
            System.out.println("获取到科目数量: " + allSubjects.size());

            // 创建更安全的科目ID到名称的映射
            Map<Integer, String> subjectMap = new HashMap<>();
            for (Subjects s : allSubjects) {
                if (s.getId() != null) {
                    subjectMap.put(s.getId(), s.getName());
                }
            }

            // 组装返回数据
            Map<String, Object> teacherInfo = new HashMap<>();
            teacherInfo.put("id", teacher.getId());
            teacherInfo.put("name", StringUtils.hasText(teacher.getName()) ? teacher.getName() : "教师" + teacher.getId()); // 使用实际名称
            // 默认头像
            teacherInfo.put("avatar", "https://api.dicebear.com/7.x/micah/svg?seed=" + teacher.getId());
            teacherInfo.put("teachingAge", teacher.getTeachingAge());

            // 根据教龄设置职称
            String title = "教师";
            if (teacher.getTeachingAge() != null) {
                if (teacher.getTeachingAge() >= 15) {
                    title = "高级教师";
                } else if (teacher.getTeachingAge() >= 8) {
                    title = "一级教师";
                }
            }
            teacherInfo.put("title", title);

            // 处理科目，支持更灵活的格式
            List<String> subjectList = new ArrayList<>();
            if (StringUtils.hasText(teacher.getSubjectIds())) {
                try {
                    // 首先尝试拆分逗号
                    String[] parts = teacher.getSubjectIds().split(",");
                    for (String part : parts) {
                        if (StringUtils.hasText(part)) {   // 过滤空值
                            try {
                                Integer subjId = Integer.parseInt(part.trim());
                                String subjectName = subjectMap.get(subjId);
                                if (subjectName != null) {
                                    subjectList.add(subjectName);
                                }
                            } catch (NumberFormatException e) {
                                // 如果解析整数失败，尝试直接匹配
                                System.out.println("警告: 科目ID格式异常: " + part);

                                // 查找ID包含此部分的科目
                                for (Map.Entry<Integer, String> entry : subjectMap.entrySet()) {
                                    if (entry.getKey().toString().contains(part.trim())) {
                                        subjectList.add(entry.getValue());
                                        break;
                                    }
                                }
                            }
                        }
                    }
                } catch (Exception e) {
                    System.out.println("科目ID解析一般错误: " + teacher.getSubjectIds() + ", " + e.getMessage());
                }

                // 如果仍然没有解析出科目，尝试整个字符串作为科目ID
                if (subjectList.isEmpty()) {
                    try {
                        Integer subjId = Integer.parseInt(teacher.getSubjectIds().trim());
                        String subjectName = subjectMap.get(subjId);
                        if (subjectName != null) {
                            subjectList.add(subjectName);
                        }
                    } catch (NumberFormatException e) {
                        System.out.println("警告: 无法解析科目ID: " + teacher.getSubjectIds());
                    }
                }
            }
            teacherInfo.put("subjects", subjectList);

            // 根据教师科目确定支持的年级
            List<Map<String, Object>> supportedGrades = new ArrayList<>();

            // 检查教师科目是否包含特定关键词，以确定支持的年级范围
            boolean isPrimarySchool = false;
            boolean isMiddleSchool = false;
            boolean isHighSchool = false;

            for (String subjectName : subjectList) {
                if (subjectName.contains("小学")) {
                    isPrimarySchool = true;
                }
                if (subjectName.contains("初中")) {
                    isMiddleSchool = true;
                }
                if (subjectName.contains("高中")) {
                    isHighSchool = true;
                }
            }

            System.out.println("教师ID: " + id + ", 科目列表: " + subjectList);
            System.out.println("初始推断学段标志 - 小学: " + isPrimarySchool + ", 初中: " + isMiddleSchool + ", 高中: " + isHighSchool);

            // 如果没有明确指明学段，根据教师信息推断
            if (!isPrimarySchool && !isMiddleSchool && !isHighSchool) {
                // 检查教师简介中是否包含学段信息
                String introduction = teacher.getIntroduction();
                boolean hasIntroduction = introduction != null && !introduction.trim().isEmpty();

                // 从简介中提取学段信息
                if (hasIntroduction) {
                    if (introduction.contains("小学")) {
                        isPrimarySchool = true;
                    }
                    if (introduction.contains("初中") || introduction.contains("中考")) {
                        isMiddleSchool = true;
                    }
                    if (introduction.contains("高中") || introduction.contains("高考")) {
                        isHighSchool = true;
                    }
                }

                // 如果仍然没有任何学段信息，默认为小学
                if (!isPrimarySchool && !isMiddleSchool && !isHighSchool) {
                    isPrimarySchool = true;
                }

                System.out.println("教师ID: " + id + ", 从介绍推断学段标志 - 小学: " + isPrimarySchool + ", 初中: " + isMiddleSchool + ", 高中: " + isHighSchool);
                System.out.println("教师介绍: " + (hasIntroduction ? introduction : "无"));
            }

            // 为小学添加年级选项
            if (isPrimarySchool) {
                for (int i = 1; i <= 6; i++) {
                    Map<String, Object> grade = new HashMap<>();
                    grade.put("id", i);
                    grade.put("name", "小学" + getChineseNumber(i) + "年级");
                    supportedGrades.add(grade);
                }
            }

            // 为初中添加年级选项
            if (isMiddleSchool) {
                for (int i = 7; i <= 9; i++) {
                    Map<String, Object> grade = new HashMap<>();
                    grade.put("id", i);
                    grade.put("name", "初中" + getChineseNumber(i-6) + "年级");
                    supportedGrades.add(grade);
                }
            }

            // 为高中添加年级选项
            if (isHighSchool) {
                for (int i = 10; i <= 12; i++) {
                    Map<String, Object> grade = new HashMap<>();
                    grade.put("id", i);
                    grade.put("name", "高中" + getChineseNumber(i-9) + "年级");
                    supportedGrades.add(grade);
                }
            }

            teacherInfo.put("supportedGrades", supportedGrades);

            // 其他信息
            teacherInfo.put("description", teacher.getIntroduction());
            teacherInfo.put("price", new BigDecimal("100")); // 实际应从课程或教师价格表获取

            return Result.success("获取教师详情成功", teacherInfo);
        } catch (Exception e) {
            System.out.println("获取教师详情异常: " + e.getMessage());
            e.printStackTrace();
            return Result.error("获取教师详情失败: " + e.getMessage());
        }
    }


    /**
     * 将数字转换为中文数字
     * @param number 阿拉伯数字
     * @return 中文数字
     */
    private String getChineseNumber(int number) {
        String[] chineseNumbers = {"零", "一", "二", "三", "四", "五", "六", "七", "八", "九", "十"};
        if (number >= 1 && number <= 10) {
            return chineseNumbers[number];
        }
        return String.valueOf(number);
    }

    /**
     * 综合搜索教师
     * @param page 页码
     * @param pageSize 每页数量
     * @param name 教师姓名（关键词）
     * @param subject 科目
     * @param minTeachingAge 最小教龄
     * @param maxTeachingAge 最大教龄
     * @param status 教师状态
     * @return 教师列表
     */
    @GetMapping({"/teachers/search", "/user/teachers/search"})
    public Result searchTeachers(
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(value = "name", required = false) String name,
            @RequestParam(value = "subject", required = false) String subject,
            @RequestParam(value = "minTeachingAge", required = false) Integer minTeachingAge,
            @RequestParam(value = "maxTeachingAge", required = false) Integer maxTeachingAge,
            @RequestParam(value = "status", required = false, defaultValue = "1") Integer status,
            @RequestParam(value = "education", required = false) String education

    ) {


        System.out.println("======= 搜索教师开始 =======");
        System.out.println("搜索教师，参数：name=" + name + ", subject=" + subject
                + ", 教龄范围=" + minTeachingAge + "-" + maxTeachingAge
                + ", status=" + status+ ", education=" + education);

        try {
            // 处理前端可能传入的特殊字符串，比如"null"字符串
            if ("null".equals(minTeachingAge)) minTeachingAge = null;
            if ("null".equals(maxTeachingAge)) maxTeachingAge = null;

            final String finalSubject;
            if ("null".equals(subject) || "全部".equals(subject)) {
                finalSubject = null;
            } else {
                finalSubject = subject;
            }
            // 后续使用finalSubject替代subject

            // 先查询所有教师，检查数据库中是否有教师记录
            List<Teachers> allTeachers = teachersService.list();
            System.out.println("数据库中总教师数量: " + allTeachers.size());
            if (allTeachers.size() > 0) {
                Teachers firstTeacher = allTeachers.get(0);
                System.out.println("示例教师数据: ID=" + firstTeacher.getId() +
                                 ", UserID=" + firstTeacher.getUserId() +
                                 ", Name=" + firstTeacher.getName() +
                                 ", SubjectIds=" + firstTeacher.getSubjectIds() +
                                 ", TeachingAge=" + firstTeacher.getTeachingAge() +
                                 ", Status=" + firstTeacher.getStatus());
            }

            // 分页参数
            Page<Teachers> pageInfo = new Page<>(page, pageSize);

            // 构建教师查询条件
            LambdaQueryWrapper<Teachers> teacherWrapper = new LambdaQueryWrapper<>();

            // 状态条件
            teacherWrapper.eq(Teachers::getStatus, status);
            System.out.println("添加条件: status=" + status);

            // 认证条件
            teacherWrapper.eq(Teachers::getCertificationStatus, 2);
            System.out.println("添加条件: certificationStatus = 2 ，已认证通过的教师");

            // 教龄范围条件
            if (minTeachingAge != null) {
                teacherWrapper.ge(Teachers::getTeachingAge, minTeachingAge);
                System.out.println("添加条件: teachingAge >= " + minTeachingAge);
            }
            if (maxTeachingAge != null) {
                teacherWrapper.le(Teachers::getTeachingAge, maxTeachingAge);
                System.out.println("添加条件: teachingAge <= " + maxTeachingAge);
            }

            // 名字条件过滤 - 使用Teachers表中的name字段
            if (StringUtils.hasText(name)) {
                // 使用Teachers表的name字段进行过滤
                teacherWrapper.like(Teachers::getName, name);
                System.out.println("添加姓名条件: name LIKE %" + name + "%");
            }

            // 科目条件
            boolean hasSubjectFilter = false;
            if (StringUtils.hasText(finalSubject)) {
                System.out.println("开始处理科目条件: " + finalSubject);

                // 获取学段前缀（如果有）
                final String levelPrefix;
                if (finalSubject.startsWith("小学")) {
                    levelPrefix = "小学";
                } else if (finalSubject.startsWith("初中")) {
                    levelPrefix = "初中";
                } else if (finalSubject.startsWith("高中")) {
                    levelPrefix = "高中";
                } else {
                    levelPrefix = null;
                }

                System.out.println("识别到学段前缀: " + levelPrefix);

                // 先查询所有科目
                List<Subjects> allSubjects = subjectsService.list();
                System.out.println("数据库中总科目数量: " + allSubjects.size());
                if (allSubjects.size() > 0) {
                    System.out.println("示例科目数据: ");
                    for (int i = 0; i < Math.min(5, allSubjects.size()); i++) {
                        Subjects sub = allSubjects.get(i);
                        System.out.println("  - ID=" + sub.getId() + ", Name=" + sub.getName());
                    }
                }

                // 1. 首先精确匹配科目名称
                LambdaQueryWrapper<Subjects> exactMatchWrapper = new LambdaQueryWrapper<>();
                exactMatchWrapper.eq(Subjects::getName, finalSubject);
                Subjects exactSubject = subjectsService.getOne(exactMatchWrapper);
                if (exactSubject != null) {
                    System.out.println("精确匹配到科目: " + exactSubject.getName() + ", ID: " + exactSubject.getId());
                    // 对于ID使用精确匹配，而不是模糊匹配
                    final Subjects finalExactSubject = exactSubject;
                    teacherWrapper.and(w ->
                        w.like(Teachers::getSubjectIds, "," + finalExactSubject.getId() + ",")
                         .or()
                         .like(Teachers::getSubjectIds, finalExactSubject.getId() + ",")
                         .or()
                         .like(Teachers::getSubjectIds, "," + finalExactSubject.getId())
                         .or()
                         .eq(Teachers::getSubjectIds, finalExactSubject.getId().toString())
                    );
                    hasSubjectFilter = true;
                } else {
                    // 2. 尝试前缀匹配，例如"小学语文"
                    LambdaQueryWrapper<Subjects> prefixMatchWrapper = new LambdaQueryWrapper<>();

                    // 如果有学段前缀，则必须匹配该学段的科目
                    if (levelPrefix != null) {
                        prefixMatchWrapper.likeRight(Subjects::getName, levelPrefix);
                    } else {
                        prefixMatchWrapper.likeRight(Subjects::getName, finalSubject);
                    }

                    List<Subjects> prefixMatchesOriginal = subjectsService.list(prefixMatchWrapper);

                    if (!prefixMatchesOriginal.isEmpty()) {
                        System.out.println("前缀匹配到 " + prefixMatchesOriginal.size() + " 个科目:");

                        // 如果有学段前缀，还需要进一步过滤匹配结果
                        final List<Subjects> prefixMatches;
                        if (levelPrefix != null) {
                            if (finalSubject.contains(",")){
                                final String[] keywords = finalSubject.split(",");
                                prefixMatches = prefixMatchesOriginal.stream()
                                        .filter(s -> s.getName() != null && Arrays.stream(keywords)
                                                .anyMatch(keyword -> s.getName().contains(keyword.trim())))
                                        .collect(Collectors.toList());
                                System.out.println("过滤后的科目数量: " + prefixMatches.size());
                            }else {
                                prefixMatches = prefixMatchesOriginal.stream()
                                        .filter(s -> s.getName().contains(finalSubject))
                                        .collect(Collectors.toList());
                                System.out.println("过滤后的科目数量: " + prefixMatches.size());
                            }

                        } else {
                            prefixMatches = prefixMatchesOriginal;
                        }

                        if (!prefixMatches.isEmpty()) {
                            teacherWrapper.and(w -> {
                                for (int i = 0; i < prefixMatches.size(); i++) {
                                    Subjects s = prefixMatches.get(i);
                                    System.out.println("  - " + s.getName() + " (ID: " + s.getId() + ")");
                                    if (i == 0) {
                                        // 对于ID使用精确匹配，而不是模糊匹配
                                        w.like(Teachers::getSubjectIds, "," + s.getId() + ",")
                                         .or()
                                         .like(Teachers::getSubjectIds, s.getId() + ",")
                                         .or()
                                         .like(Teachers::getSubjectIds, "," + s.getId())
                                         .or()
                                         .eq(Teachers::getSubjectIds, s.getId().toString());
                                    } else {
                                        w.or().like(Teachers::getSubjectIds, "," + s.getId() + ",")
                                         .or()
                                         .like(Teachers::getSubjectIds, s.getId() + ",")
                                         .or()
                                         .like(Teachers::getSubjectIds, "," + s.getId())
                                         .or()
                                         .eq(Teachers::getSubjectIds, s.getId().toString());
                                    }
                                }
                            });
                            hasSubjectFilter = true;
                        }
                    } else {
                        // 3. 如果前缀匹配也没找到，尝试模糊匹配
                        LambdaQueryWrapper<Subjects> fuzzyMatchWrapper = new LambdaQueryWrapper<>();
                        fuzzyMatchWrapper.like(Subjects::getName, finalSubject);
                        List<Subjects> fuzzyMatchesOriginal = subjectsService.list(fuzzyMatchWrapper);

                        if (!fuzzyMatchesOriginal.isEmpty()) {
                            // 如果有学段前缀，则必须匹配该学段的科目
                            final List<Subjects> fuzzyMatches;
                            if (levelPrefix != null) {
                                final String finalLevelPrefix = levelPrefix;
                                fuzzyMatches = fuzzyMatchesOriginal.stream()
                                    .filter(s -> s.getName().startsWith(finalLevelPrefix))
                                    .collect(Collectors.toList());
                                System.out.println("过滤后的模糊匹配科目数量: " + fuzzyMatches.size());
                            } else {
                                fuzzyMatches = fuzzyMatchesOriginal;
                            }

                            if (!fuzzyMatches.isEmpty()) {
                                System.out.println("模糊匹配到 " + fuzzyMatches.size() + " 个科目:");
                                teacherWrapper.and(w -> {
                                    for (int i = 0; i < fuzzyMatches.size(); i++) {
                                        Subjects s = fuzzyMatches.get(i);
                                        System.out.println("  - " + s.getName() + " (ID: " + s.getId() + ")");
                                        if (i == 0) {
                                            // 对于ID使用精确匹配，而不是模糊匹配
                                            w.like(Teachers::getSubjectIds, "," + s.getId() + ",")
                                             .or()
                                             .like(Teachers::getSubjectIds, s.getId() + ",")
                                             .or()
                                             .like(Teachers::getSubjectIds, "," + s.getId())
                                             .or()
                                             .eq(Teachers::getSubjectIds, s.getId().toString());
                                        } else {
                                            w.or().like(Teachers::getSubjectIds, "," + s.getId() + ",")
                                             .or()
                                             .like(Teachers::getSubjectIds, s.getId() + ",")
                                             .or()
                                             .like(Teachers::getSubjectIds, "," + s.getId())
                                             .or()
                                             .eq(Teachers::getSubjectIds, s.getId().toString());
                                        }
                                    }
                                });
                                hasSubjectFilter = true;
                            }
                        }
                    }
                }

                // 如果找到了科目ID，构建OR条件进行查询
                if (hasSubjectFilter) {
                    // 记录最终找到的教师
                    System.out.println("执行科目过滤查询");

                    // 打印所有教师的科目信息，帮助诊断
                    System.out.println("所有教师的科目信息：");
                    for (Teachers t : allTeachers) {
                        System.out.println("教师ID=" + t.getId() + ", 姓名=" + t.getName() + ", 科目IDs=" + t.getSubjectIds());
                    }

                    // 在结果处理阶段进行二次过滤，确保每位教师的科目列表中确实包含用户选择的科目
                    // 这是为了处理可能存在的字符串匹配问题（例如：ID为1的科目会匹配到ID为10、11等的科目）
                } else {
                    System.out.println("警告：未找到任何匹配的科目: " + finalSubject);
                    return Result.success("未找到匹配的科目", Collections.emptyMap());
                }
            }

            // 执行查询
            Page<Teachers> teacherPage = teachersService.page(pageInfo, teacherWrapper);
            System.out.println("满足条件的教师数量: " + teacherPage.getRecords().size());

            // 查询所有科目信息，用于展示教师科目名称
            List<Subjects> allSubjects = subjectsService.list();
            System.out.println("查询到科目数量: " + allSubjects.size());

            // 创建更安全的科目ID到名称的映射
            Map<Integer, String> subjectMap = new HashMap<>();
            for (Subjects s : allSubjects) {
                if (s.getId() != null) {
                    subjectMap.put(s.getId(), s.getName());
                }
            }

            // 组装返回数据
            List<Map<String, Object>> resultList = new ArrayList<>();

            // 是否需要按科目进行二次过滤
            boolean needSubjectFilter = StringUtils.hasText(finalSubject);
            // 如果有多个科目，拆分为列表
            Set<String> subjectKeywords = new HashSet<>();
            if (needSubjectFilter) {
                subjectKeywords.addAll(Arrays.stream(finalSubject.split(","))
                        .map(String::trim)
                        .filter(StringUtils::hasText)
                        .collect(Collectors.toList()));
            }

            for (Teachers teacher : teacherPage.getRecords()) {
                // 解析教师科目IDs
                List<String> teacherSubjectList = new ArrayList<>();
                List<String> teacherSubjectNames = new ArrayList<>();
                boolean matchesRequestedSubject = !needSubjectFilter; // 默认为true，除非需要过滤

                if (StringUtils.hasText(teacher.getSubjectIds())) {
                    try {
                        String[] parts = teacher.getSubjectIds().split(",");
                        for (String part : parts) {
                            if (StringUtils.hasText(part)) {
                                try {
                                    Integer subjId = Integer.parseInt(part.trim());
                                    String subjectName = subjectMap.get(subjId);
                                    if (subjectName != null) {
                                        teacherSubjectList.add(String.valueOf(subjId));
                                        teacherSubjectNames.add(subjectName);

                                        // 如果需要过滤，检查当前科目是否匹配请求的科目
                                        if ( needSubjectFilter && subjectKeywords.size()>0){
                                            if (subjectKeywords.contains(subjectName)) {
                                                matchesRequestedSubject = true;
                                            }
                                        }else if (needSubjectFilter && (subjectName.equals(finalSubject) || subjectName.contains(finalSubject))) {
                                            matchesRequestedSubject = true;
                                        }
                                    }
                                } catch (NumberFormatException e) {
                                    System.out.println("警告: 科目ID格式异常: " + part);
                                }
                            }
                        }
                    } catch (Exception e) {
                        System.out.println("科目ID解析错误: " + teacher.getSubjectIds() + ", " + e.getMessage());
                    }
                }

                // 如果教师不教授请求的科目，跳过这位教师
                if (!matchesRequestedSubject) {
                    System.out.println("跳过教师 " + teacher.getName() + "，因为其科目 " +
                                      String.join("、", teacherSubjectNames) + " 不匹配请求的科目 " + finalSubject);
                    continue;
                }

                // 检查是否遵循学段限制
                if (StringUtils.hasText(finalSubject)) {
                    // 学段前缀提取
                    final String secondLevelPrefix;
                    if (finalSubject.startsWith("小学")) {
                        secondLevelPrefix = "小学";
                    } else if (finalSubject.startsWith("初中")) {
                        secondLevelPrefix = "初中";
                    } else if (finalSubject.startsWith("高中")) {
                        secondLevelPrefix = "高中";
                    } else {
                        secondLevelPrefix = null;
                    }

                    // 如果有学段前缀，检查教师的科目是否符合该学段
                    boolean matchesLevel = false;
                    if (secondLevelPrefix != null) {
                        for (String subj : teacherSubjectNames) {
                            if (subj.startsWith(secondLevelPrefix)) {
                                matchesLevel = true;
                                break;
                            }
                        }

                        // 教师没有教授该学段的任何科目，跳过
                        if (!matchesLevel) {
                            System.out.println("跳过教师 " + teacher.getName() + "，因为其科目不包含学段 " + secondLevelPrefix);
                            continue;
                        }


                        // 如果请求的是特定科目（如"初中化学"），但教师不教这个科目，也跳过
                        boolean teachesExactSubject = teacherSubjectNames.contains(finalSubject);
                        if (subjectKeywords.size()>0){
                            for (String subjectKeyword : subjectKeywords) {
                                if (teacherSubjectNames.contains(subjectKeyword)) {
                                    teachesExactSubject = true;
                                    break;
                                }
                            }
                        }else {
                            if (!teachesExactSubject) {
                                System.out.println("跳过教师 " + teacher.getName() + "，因为不教授特定科目 " + finalSubject);
                                continue;
                            }
                        }

                    }
                }

                Map<String, Object> teacherInfo = new HashMap<>();
                teacherInfo.put("id", teacher.getId());
                teacherInfo.put("name", StringUtils.hasText(teacher.getName()) ? teacher.getName() : "教师" + teacher.getId());
                teacherInfo.put("avatar", "https://api.dicebear.com/7.x/micah/svg?seed=" + teacher.getId());
                teacherInfo.put("teachingAge", teacher.getTeachingAge());

                // 根据教龄设置职称
                String title = "教师";
                if (teacher.getTeachingAge() != null) {
                    if (teacher.getTeachingAge() >= 15) {
                        title = "高级教师";
                    } else if (teacher.getTeachingAge() >= 8) {
                        title = "一级教师";
                    }
                }
                teacherInfo.put("title", title);

                // 使用已解析的科目名称列表
                teacherInfo.put("subjects", teacherSubjectNames);
                // 添加subjectsText字段以兼容前端
                teacherInfo.put("subjectsText", String.join("、", teacherSubjectNames));

                // 其他信息
                teacherInfo.put("description", teacher.getIntroduction());
                teacherInfo.put("price", new BigDecimal("100")); // 实际应从课程或教师价格表获取
                // 放入平均分
                QueryWrapper<TeacherRating> teacherRatingQueryWrapper =new QueryWrapper<>();
                teacherRatingQueryWrapper.eq("teacher_id",teacher.getId());
                List<TeacherRating> list = teacherRatingService.list(teacherRatingQueryWrapper);

                // 计算平均分
                if (!list.isEmpty()) {
                    double avgRating = list.stream()
                            .mapToDouble(TeacherRating::getCommentRating)
                            .average()
                            .orElse(0.0);
                    teacherInfo.put("rating", Math.round(avgRating * 10.0) / 10.0);
                } else {
                    teacherInfo.put("rating", 5.0); // 默认评分
                }

                // 放入对应的教师认证信息
                QueryWrapper<TeacherCertification> teacherCertificationQueryWrapper = new QueryWrapper<>();
                teacherCertificationQueryWrapper.eq("teacher_id",teacher.getId());
                TeacherCertification certification = teacherCertificationService.getOne(teacherCertificationQueryWrapper);
                teacherInfo.put("certification", certification);
                System.out.println(certification);
                // 当前端传递学历字段的时候，匹配认证信息里面的学历字段
                if (certification != null) {
                    String teacherEducation = certification.getEducation();

                    // 判断是否满足学历筛选条件
                    if (StringUtils.hasText(education)) {  // 前端传了学历参数
                        if (StringUtils.hasText(teacherEducation) && teacherEducation.equals(education)) {
                            if (certification.getStatus() == 1) {  // 认证状态为已通过
                                resultList.add(teacherInfo);
                            }
                        }
                    } else {
                        System.out.println("前端未传递学历Dto");
                        // 如果前端未传学历参数，只判断认证是否存在即可
                        if (certification.getStatus() == 1) {
                            resultList.add(teacherInfo);
                        }
                    }
                }else {
                    System.out.println("未执行添加方法");
                }

            }

            System.out.println("返回教师数量: " + resultList.size());



            // 返回结果，包含分页信息
            Map<String, Object> result = new HashMap<>();
            result.put("records", resultList);
            result.put("total", teacherPage.getTotal());
            result.put("pages", teacherPage.getPages());
            result.put("current", teacherPage.getCurrent());
            result.put("size", teacherPage.getSize());

            return Result.success("搜索教师成功", result);
        } catch (Exception e) {
            System.out.println("搜索教师异常: " + e.getMessage());
            e.printStackTrace();
            return Result.error("搜索教师失败: " + e.getMessage());
        }
    }

    private static RealnameAuthentication  realnameAuthentication = new RealnameAuthentication();
    // 教师实名认证
    @PostMapping("/teacher/auth")
    public Result authTeacher(@RequestBody Map<String, Object> authParams) throws Exception {
        //{userId: 629575682, realName: "测试姓名", idNumber: "410581200005511017"}
        String realName = (String) authParams.get("realName");
        String idNumber = (String) authParams.get("idNumber");
        // id暂时用不到
        Integer userId = (Integer) authParams.get("userId");
        HttpResponse response = realnameAuthentication.realnameAuthentication(APPCODE, realName, idNumber);
        if (response==null){
            return Result.error("实名认证失败");
        }
        if (response.getStatusLine().getStatusCode()!=200){
            return Result.error("实名认证失败");
        }
        // 由于在realnameAuthentication方法中已经读取过response entity，流已被关闭
        // 需要重新执行请求或者修改realnameAuthentication方法避免提前消费响应流
        String authStr = EntityUtils.toString(response.getEntity());
        System.out.println("实名认证结果: " + authStr);
        // 解析JSON响应
        com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(authStr);
        com.alibaba.fastjson.JSONObject data = jsonObject.getJSONObject("data");

        if (data != null) {
            Integer result = data.getInteger("result");
            String desc = data.getString("desc");

            if (Integer.valueOf(1).equals(result)) {
                return Result.error("实名认证信息不匹配: " + desc);
            } else if (Integer.valueOf(0).equals(result)) {
                return Result.success("实名认证成功");
            } else {
                return Result.error("实名认证返回未知结果");
            }
        } else {
            return Result.error("实名认证响应格式错误");
        }


    }

//    注册教师
    /*参数
    availableDate: "2025-07-09"
    availableTime: "17:00-19:00"
    certification: {realName: "测试姓名yukino", idNumber: "410581200605130174", phone: "15993867352", email: "", education: "博士",…}
    city: "石家庄市"
    district: "长安区"
    province: "河北省"
    subjectIds: "1"
    subject_ids: "1"
    subjects: [{subjectId: 1}]
    userId: 629575681
    user_id: 629575681*/

    /**
     * 教师注册
     * @param registerParams 教师注册参数
     * @return 注册结果
     */

    @PostMapping("/teacher/register")
    @Transactional(rollbackFor = Exception.class)
    public Result registerTeacher(@RequestBody Map<String, Object> registerParams) {
        System.out.println("======= 开始教师注册 =======");
        System.out.println("注册参数: " + registerParams);

        try {
            // 获取用户ID
            Integer userId = null;
            if (registerParams.containsKey("userId")) {
                userId = Integer.valueOf(registerParams.get("userId").toString());
            } else if (registerParams.containsKey("user_id")) {
                userId = Integer.valueOf(registerParams.get("user_id").toString());
            }

            if (userId == null) {
                return Result.error("用户ID不能为空");
            }

            // 检查用户是否已注册为教师
            LambdaQueryWrapper<Teachers> checkWrapper = new LambdaQueryWrapper<>();
            checkWrapper.eq(Teachers::getUserId, userId);
            Teachers existingTeacher = teachersService.getOne(checkWrapper);
            if (existingTeacher != null) {
                return Result.error("该用户已注册为教师，请勿重复注册");
            }

            // 1. 保存教师基本信息
            Teachers teacher = new Teachers();
            teacher.setUserId(userId);

            // 获取认证信息
            Map<String, Object> certification = null;
            if (registerParams.containsKey("certification")) {
                certification = (Map<String, Object>) registerParams.get("certification");
            }

            if (certification == null) {
                return Result.error("认证信息不能为空");
            }

            // 设置教师姓名
            String realName = certification.get("realName") != null ? certification.get("realName").toString() : null;
            if (!StringUtils.hasText(realName)) {
                return Result.error("真实姓名不能为空");
            }
            teacher.setName(realName);

            String idNumber = (String) certification.get("idNumber");
            if (idNumber == null || !idNumber.matches("^\\d{17}[0-9Xx]$")) {
                return Result.error("身份证号码格式不正确");
            }

            // 调用阿里云实名认证审核

//            // 这里已经换成了客户的AccessKeyId
//            HttpResponse response = realnameAuthentication.realnameAuthentication(APPCODE, realName, idNumber);
//            String authStr = EntityUtils.toString(response.getEntity());
//            System.out.println("实名认证结果: " + authStr);
//            // 解析JSON响应
//            com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(authStr);
//            com.alibaba.fastjson.JSONObject data = jsonObject.getJSONObject("data");
//
//            if (data == null) {
//                return Result.error("实名认证响应格式错误");
//            }
//            Integer result = data.getInteger("result");
//            String desc = data.getString("desc");
//
//            if (Integer.valueOf(1).equals(result)) {
//                return Result.error("实名认证信息不匹配: " + desc);
//            } else if (!Integer.valueOf(0).equals(result)) {
//                return Result.error("实名认证返回未知结果");
//            }
//            System.out.println("实名认证成功");

            // 设置科目ID列表
            String subjectIds = (String)registerParams.get("subject_ids");

            if (!StringUtils.hasText(subjectIds)) {
                return Result.error("至少需要选择一个教授科目");
            }
            teacher.setSubjectIds(subjectIds);

            // 设置教师简介
            String introduction = certification.get("introduction") != null ?
                    certification.get("introduction").toString() : null;
            teacher.setIntroduction(StringUtils.hasText(introduction) ?
                    introduction : "这位老师很懒，还没有填写个人介绍");

            // 设置教龄

            Integer teachingAge = Optional.ofNullable((Integer) certification.get("teachingYears")).orElse(0);

            teacher.setTeachingAge(teachingAge);

            // 设置认证状态（1- 待认证）
            teacher.setCertificationStatus(1);

            // 设置教师状态（1-正常）
            teacher.setStatus(1);

            // 设置地址信息
            String province = registerParams.get("province") != null ?
                    registerParams.get("province").toString() : null;
            String city = registerParams.get("city") != null ?
                    registerParams.get("city").toString() : null;
            String district = registerParams.get("district") != null ?
                    registerParams.get("district").toString() : null;
            String detailAddr = registerParams.get("detailAddr") != null ?
                    registerParams.get("detailAddr").toString() :
                    (registerParams.get("detailedAddress") != null ?
                     registerParams.get("detailedAddress").toString() : null);

            // 设置地址字段
            teacher.setProvince(province);
            teacher.setCity(city);
            teacher.setDistrict(district);
            teacher.setDetailAddr(detailAddr);

            // 设置经纬度坐标
            Double latitude = null;
            Double longitude = null;

            if (registerParams.get("latitude") != null) {
                try {
                    latitude = Double.valueOf(registerParams.get("latitude").toString());
                } catch (NumberFormatException e) {
                    System.out.println("纬度格式错误: " + registerParams.get("latitude"));
                }
            }

            if (registerParams.get("longitude") != null) {
                try {
                    longitude = Double.valueOf(registerParams.get("longitude").toString());
                } catch (NumberFormatException e) {
                    System.out.println("经度格式错误: " + registerParams.get("longitude"));
                }
            }

            // 如果前端提供了有效的经纬度，使用前端数据；否则设置默认值
            teacher.setLatitude(latitude != null && latitude != 0.0 ? latitude : 0.0);
            teacher.setLongitude(longitude != null && longitude != 0.0 ? longitude : 0.0);

            System.out.println("地址信息设置完成: province=" + province + ", city=" + city +
                             ", district=" + district + ", detailAddr=" + detailAddr);
            System.out.println("坐标信息设置完成: latitude=" + teacher.getLatitude() +
                             ", longitude=" + teacher.getLongitude());


            // 保存教师手机号和邮箱
//            teacher.setPhone(registerParams.get("phone") != null ? registerParams.get("phone").toString() : null);
//            teacher.setEmail(registerParams.get("email") != null ? registerParams.get("email").toString() : null);


            // 保存教师基本信息 !!!
            boolean saveTeacherResult = teachersService.save(teacher);
            if (!saveTeacherResult) {
                throw new Exception("保存教师基本信息失败");
            }

            // 2. 保存教师认证信息 todo
            TeacherCertification teacherCert = new TeacherCertification();
            // 设置认证表 id
            teacherCert.setTeacherId(teacher.getId());
            // 设置身份证号
            teacherCert.setIdNumber(idNumber);

            // 校验手机号
            String phone = (String) certification.get("phone");
            if (phone == null || !phone.matches("^1[3-9]\\d{9}$")) {
                throw new Exception("手机号码格式不正确");
            }
            teacherCert.setPhone(phone);

            // 校验邮箱
            String email = certification.containsKey("email") ? certification.get("email").toString() : null;
            if (StringUtils.hasText(email) && !email.matches("^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$")) {
                return Result.error("邮箱格式不正确");
            }
            teacherCert.setEmail(email);

            // 设置学历
            String education = (String) certification.get("education");
            if (!StringUtils.hasText(education)){
                throw new Exception("学历不能为空");
            }
            teacherCert.setEducation(education);

            // 这是专业
            String major = (String) certification.get("major");
            if (!StringUtils.hasText(major)){
                throw new Exception("专业不能为空");
            }
            teacherCert.setMajor(major);

            // 毕业院校
            String graduateSchool = (String) certification.get("graduateSchool");
            if (!StringUtils.hasText(graduateSchool)){
                throw new Exception("毕业院校不能为空");
            }
            teacherCert.setGraduateSchool(graduateSchool);

            // 设置身份证正反面
            teacherCert.setIdCardBack((String) certification.get("idCardBack")); //todo 这里是默认值
            teacherCert.setIdCardFront((String) certification.get("idCardFront"));
            // 设置文凭
            teacherCert.setDiplomaImg((String) certification.get("diplomaImg"));
            // 设置教师证书
            String teacherCertImg = (String) certification.get("teacherCertImg");
            teacherCert.setTeacherCertImg(teacherCertImg);
            // 设置教龄
//            teacherCert.setTeachingYears(teachingAge);

            // 设置认证状态（0-待审核）
            teacherCert.setStatus(0);

            // 设置创建和更新时间
            Date now = new Date();
            teacherCert.setCreateTime(now);
            teacherCert.setUpdateTime(now);

            // 设置删除标记（0-未删除）
            teacherCert.setIsDeleted(0);

            // 保存认证信息
            boolean saveCertResult = teacherCertificationService.save(teacherCert);
            if (!saveCertResult) {
                // 如果认证信息保存失败，回滚教师信息
                teachersService.removeById(teacher.getId());
                throw new Exception("保存教师认证信息失败");
            }

            // 3. 返回结果
            Map<String, Object> resultData = new HashMap<>();
            resultData.put("teacherId", teacher.getId());
            resultData.put("certificationId", teacherCert.getId());
            resultData.put("status", "待审核");

            System.out.println("教师注册成功，ID: " + teacher.getId());

            // 更改用户表的 用户角色
            usersService.update().set("role", 2).eq("id", userId).update();

            return Result.success("教师注册申请提交成功，等待管理员审核", resultData);

        } catch (Exception e) {
            System.out.println("教师注册异常: " + e.getMessage());
            e.printStackTrace();
            throw new RuntimeException("教师注册失败", e);
        }
    }

    @Autowired
    private MinioClient minioClient;

    // 教书注册上传图片
    @PostMapping("/teacher/upload-certificate")
    @SneakyThrows
    public Result uploadCertificate(@RequestParam("file") MultipartFile certificate,@RequestParam("type") String type) {
        // 将文件上传至minio
//        MinioClient minioClient = MinioClient.builder()
//                .endpoint("http://192.168.183.128:19001")
//                .credentials("minioadmin2", "minioadmin2")
//                .build();

        InputStream inputStream = certificate.getInputStream();
        String uuid = UUID.randomUUID().toString();

        PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                //type+certificate.getOriginalFilename() 获取原始名
                .object(uuid)
                .contentType(certificate.getContentType())
                .stream(inputStream,inputStream.available(), -1)
                .bucket("teacher-manage")
                .build();
        minioClient.putObject(putObjectArgs);
        String url = minioClient.getObjectUrl("teacher-manage", uuid);
        if (!url.isEmpty()){
            return Result.success("上传成功",url);
        }
        return Result.error("上传失败");


    }


    /*
    * 根据用户id 获取认证状态信息
    * /certification/status
    * */
    @GetMapping("/teacher/certification/status")
    public Result getCertificationStatus(@RequestParam("userId") Integer userId) {
        // 首先获取教师id
        QueryWrapper<Teachers> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        Teachers teacher = teachersService.getOne(wrapper);
        if (teacher == null) {
            return Result.error("用户不存在");
        }
        QueryWrapper<TeacherCertification> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("teacher_id", teacher.getId());
        TeacherCertification teacherCertification = teacherCertificationService.getOne(wrapper1);
        return Result.success("获取教师信息成功", teacherCertification);
    }

    @GetMapping("/teacher/students")
    public Result getTeachersStudent(@RequestParam("userId") Integer userId) {
        try {
            System.out.println("获取教师学生信息，用户ID: " + userId);

            // 1. 根据用户ID查询教师信息
            LambdaQueryWrapper<Teachers> teacherWrapper = new LambdaQueryWrapper<>();
            teacherWrapper.eq(Teachers::getUserId, userId);
            Teachers teacher = teachersService.getOne(teacherWrapper);

            if (teacher == null) {
                return Result.error("教师信息不存在");
            }

            System.out.println("找到教师信息，教师ID: " + teacher.getId());

            // 2. 根据教师ID查询已付款的订单（状态为3）
            LambdaQueryWrapper<Order> orderWrapper = new LambdaQueryWrapper<>();
            orderWrapper.eq(Order::getTeacherId, teacher.getId())
                       .eq(Order::getStatus, 3) // 状态为3表示已付款
                       .orderByDesc(Order::getCreatedAt);

            List<Order> orders = ordersService.list(orderWrapper);
            System.out.println("找到已付款订单数量: " + orders.size());

            if (orders.isEmpty()) {
                return Result.success("获取成功", new ArrayList<>());
            }

            // 3. 组装返回数据
            List<Map<String, Object>> resultList = new ArrayList<>();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

            for (Order order : orders) {
                // 查询学生信息
                Users student = usersService.getById(order.getUserId());
                if (student == null) {
                    continue; // 跳过无效的学生记录
                }

                // 查询课程信息
                Courses course = coursesService.getById(order.getCourseId());
                if (course == null) {
                    continue; // 跳过无效的课程记录
                }

                // 查询预约信息（如果有booking_id）
                Bookings booking = null;
                if (order.getBookingId() != null) {
                    booking = bookingsService.getById(order.getBookingId());
                    log.info("查询预约信息成功, bookingId={}", order.getBookingId());
                }
                if (booking.getStatus()==0 || booking.getStatus()==2){
                    // 待支付 和 已取消的不展示
                    break;
                }


                // 组装数据
                Map<String, Object> studentInfo = new HashMap<>();
                studentInfo.put("id", order.getBookingId() != null ? order.getBookingId().toString() : "order_" + order.getId());
                studentInfo.put("studentId", student.getId().toString());
                studentInfo.put("studentName", student.getNickname() != null ? student.getNickname() : "学生" + student.getId());
                studentInfo.put("studentPhone", student.getPhone());
                studentInfo.put("avatarUrl", student.getAvatarUrl() != null ? student.getAvatarUrl() :
                    "https://api.dicebear.com/7.x/micah/svg?seed=" + student.getId());

                studentInfo.put("courseId", course.getId().toString());
                studentInfo.put("courseTitle", course.getTitle());

                // 如果有预约信息，使用预约信息；否则使用默认值
                if (booking != null) {
                    studentInfo.put("grade", booking.getGrade() != null ? booking.getGrade() : "未知年级");
                    studentInfo.put("province", booking.getProvince() != null ? booking.getProvince() : "");
                    studentInfo.put("city", booking.getCity() != null ? booking.getCity() : "");
                    studentInfo.put("district", booking.getDistrict() != null ? booking.getDistrict() : "");
                    studentInfo.put("detailedAddress", booking.getDetailedAddress() != null ? booking.getDetailedAddress() : "");
                    studentInfo.put("bookingDate", booking.getBookingDate() != null ? booking.getBookingDate().toString() : "");
                    studentInfo.put("timeSlot", booking.getTimeSlot() != null ? booking.getTimeSlot() : "");
                    studentInfo.put("price", booking.getPrice() != null ? booking.getPrice() : order.getAmount());
                    studentInfo.put("detailAddress",booking.getDetailedAddress());
                } else {
                    // 使用默认值
                    studentInfo.put("grade", "未知年级");
                    studentInfo.put("province", "");
                    studentInfo.put("city", "");
                    studentInfo.put("district", "");
                    studentInfo.put("detailedAddress", "");
                    studentInfo.put("bookingDate", "");
                    studentInfo.put("timeSlot", "");
                    studentInfo.put("price", order.getAmount());
                }

                studentInfo.put("status", booking.getStatus()); // 1-进行中（因为查询的是已付款订单）
                studentInfo.put("createTime", order.getCreatedAt() != null ?
                    order.getCreatedAt().format(formatter) : "");
                studentInfo.put("updateTime", order.getPaidAt() != null ?
                    order.getPaidAt().format(formatter) : "");

                resultList.add(studentInfo);
            }

            System.out.println("成功组装学生信息数量: " + resultList.size());
            return Result.success("获取成功", resultList);

        } catch (Exception e) {
            System.err.println("获取教师学生信息异常: " + e.getMessage());
            e.printStackTrace();
            return Result.error("获取教师学生信息失败: " + e.getMessage());
        }
    }

    // 完成授课
    @PostMapping("/teacher/course/complete")
    public Result completeCourse(@RequestBody Map<String, Object> params) {
        // 安全地获取 bookingId 参数
        Object bookingIdObj = params.get("bookingId");
        if (bookingIdObj == null) {
            return Result.error("参数错误：缺少预约ID");
        }

        Integer bookingId;
        try {
            // 尝试转换为 Integer 类型
            if (bookingIdObj instanceof Integer) {
                bookingId = (Integer) bookingIdObj;
            } else {
                bookingId = Integer.valueOf(bookingIdObj.toString());
            }
        } catch (NumberFormatException e) {
            return Result.error("参数错误：预约ID格式不正确");
        }

        // 将 预约的 状态改为 3，已经上完
        LambdaUpdateWrapper<Bookings> updateWrapper = new LambdaUpdateWrapper<>();
        boolean b = bookingsService.updateBookingStatus(bookingId, 3);
        if (b){
            return Result.success("完成授课成功",bookingId);
        }
        return Result.error("完成授课失败,找不到对应的预约信息");

    }

    // 教师评价
    @PostMapping("/teacher/evaluate")
    public Result evaluateTeacher(@RequestBody TeacherRatingRequest ratingRequest) {
        try {
            System.out.println("收到教师评价请求：" + ratingRequest);
            return teacherRatingService.submitRating(ratingRequest);
        } catch (Exception e) {
            System.err.println("教师评价异常：" + e.getMessage());
            e.printStackTrace();
            return Result.error("评价提交失败：" + e.getMessage());
        }
    }

    // 教师排行榜
    @GetMapping("/teacher/ranking")
    public Result getTeacherRanking(@RequestParam(value = "limit", defaultValue = "10") Integer limit) {
        try {
            System.out.println("获取教师排行榜，限制数量：" + limit);
            return teacherRatingService.getTeacherRanking(limit);
        } catch (Exception e) {
            System.err.println("获取教师排行榜异常：" + e.getMessage());
            e.printStackTrace();
            return Result.error("获取排行榜失败：" + e.getMessage());
        }
    }

    // 清除排行榜缓存
    @PostMapping("/teacher/ranking/clear-cache")
    public Result clearRankingCache() {
        try {
            System.out.println("手动清除排行榜缓存");
            teacherRatingService.clearRankingCache();
            return Result.success("缓存清除成功");
        } catch (Exception e) {
            System.err.println("清除排行榜缓存异常：" + e.getMessage());
            e.printStackTrace();
            return Result.error("清除缓存失败：" + e.getMessage());
        }
    }

    /**
     * 获取附近的教师
     * @param latitude 纬度
     * @param longitude 经度
     * @param radius 搜索半径（千米）
     * @param page 页码
     * @param size 每页大小
     * @return 附近教师列表
     */
    @GetMapping("/user/teachers/nearby")
    public Result getNearbyTeachers(
            @RequestParam(value = "latitude") Double latitude,
            @RequestParam(value = "longitude") Double longitude,
            @RequestParam(value = "radius", defaultValue = "5") Double radius,
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "size", defaultValue = "20") Integer size) {

        System.out.println("======= 获取附近教师 =======");
        System.out.println("搜索参数: latitude=" + latitude + ", longitude=" + longitude +
                          ", radius=" + radius + "km, page=" + page + ", size=" + size);

        try {
            // 1. 参数校验
            if (!com.zt.utils.GeoUtils.isValidCoordinate(latitude, longitude)) {
                return Result.error("经纬度坐标无效");
            }

            if (radius == null || radius <= 0 || radius > 50) {
                return Result.error("搜索半径必须在0-50公里之间");
            }

            // 2. 查询所有已认证的教师
            LambdaQueryWrapper<Teachers> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Teachers::getStatus, 1) // 正常状态
                   .eq(Teachers::getCertificationStatus, 2) // 已认证
                   .isNotNull(Teachers::getLatitude)
                   .isNotNull(Teachers::getLongitude);

            List<Teachers> allTeachers = teachersService.list(wrapper);
            System.out.println("查询到已认证教师数量: " + allTeachers.size());

            if (allTeachers.isEmpty()) {
                Map<String, Object> emptyResult = new HashMap<>();
                emptyResult.put("records", new ArrayList<>());
                emptyResult.put("total", 0);
                emptyResult.put("pages", 0);
                emptyResult.put("current", page);
                emptyResult.put("size", size);
                emptyResult.put("pagination", createPagination(page, size, 0));
                emptyResult.put("searchInfo", createSearchInfo(latitude, longitude, radius, 0));
                return Result.success("获取成功", emptyResult);
            }

            // 3. 计算距离并筛选在半径内的教师
            List<Map<String, Object>> nearbyTeachers = new ArrayList<>();

            for (Teachers teacher : allTeachers) {
                if (teacher.getLatitude() != null && teacher.getLongitude() != null) {
                    double distance = com.zt.utils.GeoUtils.calculateDistance(
                        latitude, longitude,
                        teacher.getLatitude(), teacher.getLongitude()
                    );

                    // 只保留在指定半径内的教师
                    if (distance <= radius) {
                        Map<String, Object> teacherInfo = buildTeacherInfo(teacher, distance);
                        nearbyTeachers.add(teacherInfo);
                    }
                }
            }

            System.out.println("半径内教师数量: " + nearbyTeachers.size());

            // 4. 按距离排序
            nearbyTeachers.sort((t1, t2) -> {
                Double dist1 = (Double) ((Map<String, Object>) t1.get("location")).get("distance");
                Double dist2 = (Double) ((Map<String, Object>) t2.get("location")).get("distance");
                return Double.compare(dist1, dist2);
            });

            // 5. 分页处理
            int total = nearbyTeachers.size();
            int startIndex = (page - 1) * size;
            int endIndex = Math.min(startIndex + size, total);

            List<Map<String, Object>> pagedTeachers = new ArrayList<>();
            if (startIndex < total) {
                pagedTeachers = nearbyTeachers.subList(startIndex, endIndex);
            }

            // 6. 构建返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("data", pagedTeachers);
            result.put("pagination", createPagination(page, size, total));
            result.put("searchInfo", createSearchInfo(latitude, longitude, radius, total));

            return Result.success("获取成功", result);

        } catch (Exception e) {
            System.err.println("获取附近教师异常: " + e.getMessage());
            e.printStackTrace();
            return Result.error("获取附近教师失败: " + e.getMessage());
        }
    }

    /**
     * 构建教师信息
     */
    private Map<String, Object> buildTeacherInfo(Teachers teacher, double distance) {
        Map<String, Object> teacherInfo = new HashMap<>();

        // 基本信息
        teacherInfo.put("id", teacher.getId());
        teacherInfo.put("name", StringUtils.hasText(teacher.getName()) ? teacher.getName() : "教师" + teacher.getId());
        teacherInfo.put("avatar", "https://api.dicebear.com/7.x/micah/svg?seed=" + teacher.getId());

        // 职称
        String title = "教师";
        if (teacher.getTeachingAge() != null) {
            if (teacher.getTeachingAge() >= 15) {
                title = "特级教师";
            } else if (teacher.getTeachingAge() >= 8) {
                title = "高级教师";
            } else if (teacher.getTeachingAge() >= 3) {
                title = "一级教师";
            }
        }
        teacherInfo.put("title", title);

        // 科目信息
        List<String> subjects = parseTeacherSubjects(teacher.getSubjectIds());
        teacherInfo.put("subjects", subjects);
        teacherInfo.put("subjectsText", String.join("、", subjects));

        // 年级信息
        String grade = determineGrade(subjects);
        teacherInfo.put("grade", grade);

        // 简介
        teacherInfo.put("description", StringUtils.hasText(teacher.getIntroduction()) ?
            teacher.getIntroduction() : "这位老师很优秀，但还没有填写个人介绍");

        // 价格（这里使用默认值，实际应该从课程表或价格表获取）
        teacherInfo.put("price", 180);

        // 评分和评价数量
        Map<String, Object> ratingInfo = getTeacherRating(teacher.getId());
        teacherInfo.put("rating", ratingInfo.get("rating"));
        teacherInfo.put("reviewCount", ratingInfo.get("reviewCount"));

        // 教龄
        teacherInfo.put("teachingAge", teacher.getTeachingAge() != null ? teacher.getTeachingAge() : 0);

        // 位置信息
        Map<String, Object> location = new HashMap<>();
        location.put("latitude", teacher.getLatitude());
        location.put("longitude", teacher.getLongitude());
        location.put("address", "位置信息"); // 这里可以根据经纬度反向地理编码获取地址
        location.put("distance", Math.round(distance * 10.0) / 10.0); // 保留一位小数
        teacherInfo.put("location", location);

        // 在线状态（模拟数据）
        teacherInfo.put("isOnline", Math.random() > 0.3); // 70%概率在线
        teacherInfo.put("responseTime", Math.random() > 0.5 ? "5分钟内" : "1小时内");

        // 标签
        List<String> tags = generateTeacherTags(teacher);
        teacherInfo.put("tags", tags);

        // 认证信息
        Map<String, Object> certification = new HashMap<>();
        certification.put("hasTeacherCert", true);
        certification.put("hasIdVerified", true);
        certification.put("hasBackgroundCheck", true);
        teacherInfo.put("certification", certification);

        // 时间安排
        Map<String, Object> schedule = new HashMap<>();
        schedule.put("availableToday", Math.random() > 0.4); // 60%概率今天有空
        schedule.put("nextAvailableTime", "2024-01-15 14:00:00"); // 这里应该从实际的时间安排表获取
        teacherInfo.put("schedule", schedule);

        return teacherInfo;
    }

    /**
     * 解析教师科目
     */
    private List<String> parseTeacherSubjects(String subjectIds) {
        List<String> subjects = new ArrayList<>();

        if (!StringUtils.hasText(subjectIds)) {
            return subjects;
        }

        try {
            // 获取所有科目映射
            List<Subjects> allSubjects = subjectsService.list();
            Map<Integer, String> subjectMap = new HashMap<>();
            for (Subjects s : allSubjects) {
                if (s.getId() != null) {
                    subjectMap.put(s.getId(), s.getName());
                }
            }

            // 解析科目ID
            String[] parts = subjectIds.split(",");
            for (String part : parts) {
                if (StringUtils.hasText(part)) {
                    try {
                        Integer subjId = Integer.parseInt(part.trim());
                        String subjectName = subjectMap.get(subjId);
                        if (subjectName != null) {
                            subjects.add(subjectName);
                        }
                    } catch (NumberFormatException e) {
                        System.out.println("警告: 科目ID格式异常: " + part);
                    }
                }
            }
        } catch (Exception e) {
            System.out.println("解析教师科目异常: " + e.getMessage());
        }

        return subjects.isEmpty() ? List.of("未知科目") : subjects;
    }

    /**
     * 根据科目确定年级
     */
    private String determineGrade(List<String> subjects) {
        for (String subject : subjects) {
            if (subject.contains("小学")) {
                return "小学";
            } else if (subject.contains("初中")) {
                return "初中";
            } else if (subject.contains("高中")) {
                return "高中";
            }
        }
        return "小学"; // 默认
    }

    /**
     * 获取教师评分信息
     */
    private Map<String, Object> getTeacherRating(Integer teacherId) {
        Map<String, Object> ratingInfo = new HashMap<>();

        try {
            // 查询教师评价
            LambdaQueryWrapper<TeacherRating> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(TeacherRating::getTeacherId, teacherId);
            List<TeacherRating> ratings = teacherRatingService.list(wrapper);

            if (ratings.isEmpty()) {
                ratingInfo.put("rating", 5.0);
                ratingInfo.put("reviewCount", 0);
            } else {
                double avgRating = ratings.stream()
                    .mapToDouble(TeacherRating::getCommentRating)
                    .average()
                    .orElse(5.0);
                ratingInfo.put("rating", Math.round(avgRating * 10.0) / 10.0);
                ratingInfo.put("reviewCount", ratings.size());
            }
        } catch (Exception e) {
            System.out.println("获取教师评分异常: " + e.getMessage());
            ratingInfo.put("rating", 5.0);
            ratingInfo.put("reviewCount", 0);
        }

        return ratingInfo;
    }

    /**
     * 生成教师标签
     */
    private List<String> generateTeacherTags(Teachers teacher) {
        List<String> tags = new ArrayList<>();

        if (teacher.getTeachingAge() != null) {
            if (teacher.getTeachingAge() >= 10) {
                tags.add("经验丰富");
            }
            if (teacher.getTeachingAge() >= 5) {
                tags.add("耐心细致");
            }
        }

        // 根据评分添加标签
        Map<String, Object> ratingInfo = getTeacherRating(teacher.getId());
        Double rating = (Double) ratingInfo.get("rating");
        if (rating >= 4.8) {
            tags.add("提分显著");
        }
        if (rating >= 4.5) {
            tags.add("学生喜爱");
        }

        // 默认标签
        if (tags.isEmpty()) {
            tags.add("认真负责");
        }

        return tags;
    }

    /**
     * 创建分页信息
     */
    private Map<String, Object> createPagination(Integer page, Integer size, Integer total) {
        Map<String, Object> pagination = new HashMap<>();

        int pages = (int) Math.ceil((double) total / size);

        pagination.put("page", page);
        pagination.put("size", size);
        pagination.put("total", total);
        pagination.put("pages", pages);
        pagination.put("hasNext", page < pages);
        pagination.put("hasPrev", page > 1);

        return pagination;
    }

    /**
     * 创建搜索信息
     */
    private Map<String, Object> createSearchInfo(Double latitude, Double longitude, Double radius, Integer totalTeachers) {
        Map<String, Object> searchInfo = new HashMap<>();

        searchInfo.put("searchRadius", radius);

        Map<String, Object> centerLocation = new HashMap<>();
        centerLocation.put("latitude", latitude);
        centerLocation.put("longitude", longitude);
        centerLocation.put("address", "搜索中心位置"); // 这里可以通过反向地理编码获取地址
        searchInfo.put("centerLocation", centerLocation);

        searchInfo.put("totalTeachersInRadius", totalTeachers);
        searchInfo.put("searchTime", new java.util.Date());

        return searchInfo;
    }


    // 设置教师可用时间

    /**
     * 添加教师可用时间
     * @param request 请求参数
     * @return 操作结果
     */
    @PostMapping("/teacher/available-time/add")
    public Result addTeacherAvailableTime(@RequestBody TeacherAvailableRequest request) {
        System.out.println("======= 添加教师可用时间 =======");
        System.out.println("请求参数: " + request);

        try {
            // 参数校验
            if (request.getUserId() == null && request.getTeacherId() == null) {
                return Result.error("用户ID或教师ID不能为空");
            }

            Integer teacherId = request.getTeacherId();

            // 如果没有传教师ID，通过用户ID查找教师ID
            if (teacherId == null && request.getUserId() != null) {
                LambdaQueryWrapper<Teachers> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(Teachers::getUserId, request.getUserId());
                Teachers teacher = teachersService.getOne(wrapper);
                if (teacher == null) {
                    return Result.error("该用户不是教师");
                }
                teacherId = teacher.getId();
            }

            if (request.getAvailableTime() == null) {
                return Result.error("可用时间不能为空");
            }

            if (request.getStatus() == null) {
                request.setStatus(1); // 默认为长期教师
            }

            // 添加可用时间
            boolean success = teacherAvailableService.addAvailableTime(
                    teacherId,
                    request.getAvailableTime(),
                    request.getStatus()
            );

            if (success) {
                return Result.success("添加教师可用时间成功");
            } else {
                return Result.error("添加教师可用时间失败");
            }

        } catch (Exception e) {
            System.out.println("添加教师可用时间异常: " + e.getMessage());
            e.printStackTrace();
            return Result.error("添加教师可用时间失败: " + e.getMessage());
        }
    }

    /**
     * 批量添加教师可用时间
     * @param request 请求参数
     * @return 操作结果
     */
    @PostMapping("/teacher/available-time/batch-add")
    public Result batchAddTeacherAvailableTime(@RequestBody TeacherAvailableRequest request) {
        System.out.println("======= 批量添加教师可用时间 =======");
        System.out.println("请求参数: " + request);

        try {
            // 参数校验
            if (request.getUserId() == null && request.getTeacherId() == null) {
                return Result.error("用户ID或教师ID不能为空");
            }

            Integer teacherId = request.getTeacherId();

            // 如果没有传教师ID，通过用户ID查找教师ID
            if (teacherId == null && request.getUserId() != null) {
                LambdaQueryWrapper<Teachers> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(Teachers::getUserId, request.getUserId());
                Teachers teacher = teachersService.getOne(wrapper);
                if (teacher == null) {
                    return Result.error("该用户不是教师");
                }
                teacherId = teacher.getId();
            }

            if (request.getAvailableTimes() == null || request.getAvailableTimes().isEmpty()) {
                return Result.error("可用时间列表不能为空");
            }

            if (request.getStatus() == null) {
                request.setStatus(1); // 默认为长期教师
            }

            // 批量添加可用时间
            boolean success = teacherAvailableService.batchAddAvailableTimes(
                    teacherId,
                    request.getAvailableTimes(),
                    request.getStatus()
            );

            if (success) {
                return Result.success("批量添加教师可用时间成功");
            } else {
                return Result.error("批量添加教师可用时间失败");
            }

        } catch (Exception e) {
            System.out.println("批量添加教师可用时间异常: " + e.getMessage());
            e.printStackTrace();
            return Result.error("批量添加教师可用时间失败: " + e.getMessage());
        }
    }

    /**
     * 查询教师可用时间
     * @param userIdStr 用户ID字符串
     * @param teacherIdStr 教师ID字符串
     * @return 可用时间列表
     */
    @GetMapping("/teacher/available-time/list")
    public Result getTeacherAvailableTime(
            @RequestParam(value = "userId", required = false) String userIdStr,
            @RequestParam(value = "teacherId", required = false) String teacherIdStr) {

        System.out.println("======= 查询教师可用时间 =======");
        System.out.println("用户ID: " + userIdStr + ", 教师ID: " + teacherIdStr);

        try {
            // 参数转换和校验
            Integer userId = parseIntegerParam(userIdStr);
            Integer teacherId = parseIntegerParam(teacherIdStr);

            if (userId == null && teacherId == null) {
                return Result.error("用户ID或教师ID不能为空");
            }

            Integer finalTeacherId = teacherId;

            // 如果没有传教师ID，通过用户ID查找教师ID
            if (finalTeacherId == null && userId != null) {
                LambdaQueryWrapper<Teachers> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(Teachers::getUserId, userId);
                Teachers teacher = teachersService.getOne(wrapper);
                if (teacher == null) {
                    return Result.error("该用户不是教师");
                }
                finalTeacherId = teacher.getId();
            }

            // 查询可用时间
            List<TeacherAvailable> availableTimes = teacherAvailableService.getAvailableTimesByTeacherId(finalTeacherId);

            return Result.success("查询教师可用时间成功", availableTimes);

        } catch (Exception e) {
            System.out.println("查询教师可用时间异常: " + e.getMessage());
            e.printStackTrace();
            return Result.error("查询教师可用时间失败: " + e.getMessage());
        }
    }

    /**
     * 删除教师可用时间
     * @param request 请求参数
     * @return 操作结果
     */
    @PostMapping("/teacher/available-time/remove")
    public Result removeTeacherAvailableTime(@RequestBody TeacherAvailableRequest request) {
        System.out.println("======= 删除教师可用时间 =======");
        System.out.println("请求参数: " + request);

        try {
            // 参数校验
            if (request.getUserId() == null && request.getTeacherId() == null) {
                return Result.error("用户ID或教师ID不能为空");
            }

            Integer teacherId = request.getTeacherId();

            // 如果没有传教师ID，通过用户ID查找教师ID
            if (teacherId == null && request.getUserId() != null) {
                LambdaQueryWrapper<Teachers> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(Teachers::getUserId, request.getUserId());
                Teachers teacher = teachersService.getOne(wrapper);
                if (teacher == null) {
                    return Result.error("该用户不是教师");
                }
                teacherId = teacher.getId();
            }

            if (request.getAvailableTime() == null) {
                return Result.error("要删除的可用时间不能为空");
            }

            // 删除可用时间
            boolean success = teacherAvailableService.removeAvailableTime(
                    teacherId,
                    request.getAvailableTime()
            );

            if (success) {
                return Result.success("删除教师可用时间成功");
            } else {
                return Result.error("删除教师可用时间失败");
            }

        } catch (Exception e) {
            System.out.println("删除教师可用时间异常: " + e.getMessage());
            e.printStackTrace();
            return Result.error("删除教师可用时间失败: " + e.getMessage());
        }
    }

    /**
     * 申请成为长期教师
     * @param request 请求参数
     * @return 操作结果
     */
    @PostMapping("/teacher/apply-long-term")
    public Result applyForLongTermTeacher(@RequestBody TeacherAvailableRequest request) {
        System.out.println("======= 申请成为长期教师 =======");
        System.out.println("请求参数: " + request);

        try {
            // 参数校验
            if (request.getUserId() == null && request.getTeacherId() == null) {
                return Result.error("用户ID或教师ID不能为空");
            }

            Integer teacherId = request.getTeacherId();

            // 如果没有传教师ID，通过用户ID查找教师ID
            if (teacherId == null && request.getUserId() != null) {
                LambdaQueryWrapper<Teachers> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(Teachers::getUserId, request.getUserId());
                Teachers teacher = teachersService.getOne(wrapper);
                if (teacher == null) {
                    return Result.error("该用户不是教师");
                }
                teacherId = teacher.getId();
            }

            // 检查是否已有待审核的申请
            TeacherAvailable existingApplication = teacherAvailableService.getLongTermApplicationByTeacherId(teacherId);
            if (existingApplication != null && existingApplication.getAuditStatus().equals(0)) {
                return Result.error("您已有待审核的长期教师申请，请耐心等待审核结果");
            }

            // 提交申请
            boolean success = teacherAvailableService.applyForLongTermTeacher(teacherId);

            if (success) {
                return Result.success("长期教师申请提交成功，请等待管理员审核");
            } else {
                return Result.error("长期教师申请提交失败");
            }

        } catch (Exception e) {
            System.out.println("申请成为长期教师异常: " + e.getMessage());
            e.printStackTrace();
            return Result.error("申请成为长期教师失败: " + e.getMessage());
        }
    }



    /**
     * 查询教师的长期教师申请状态
     * @param userIdStr 用户ID字符串
     * @param teacherIdStr 教师ID字符串
     * @return 申请状态
     */
    @GetMapping("/teacher/long-term-application-status")
    public Result getLongTermApplicationStatus(
            @RequestParam(value = "userId", required = false) String userIdStr,
            @RequestParam(value = "teacherId", required = false) String teacherIdStr) {

        System.out.println("======= 查询长期教师申请状态 =======");
        System.out.println("用户ID: " + userIdStr + ", 教师ID: " + teacherIdStr);

        try {
            // 参数转换和校验
            Integer userId = parseIntegerParam(userIdStr);
            Integer teacherId = parseIntegerParam(teacherIdStr);

            if (userId == null && teacherId == null) {
                return Result.error("用户ID或教师ID不能为空");
            }

            Integer finalTeacherId = teacherId;

            // 如果没有传教师ID，通过用户ID查找教师ID
            if (finalTeacherId == null && userId != null) {
                LambdaQueryWrapper<Teachers> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(Teachers::getUserId, userId);
                Teachers teacher = teachersService.getOne(wrapper);
                if (teacher == null) {
                    return Result.error("该用户不是教师");
                }
                finalTeacherId = teacher.getId();
            }

            // 查询申请状态
            TeacherAvailable application = teacherAvailableService.getLongTermApplicationByTeacherId(finalTeacherId);

            Map<String, Object> statusInfo = new HashMap<>();
            if (application != null) {
                statusInfo.put("hasApplication", true);
                statusInfo.put("auditStatus", application.getAuditStatus());
                statusInfo.put("auditComment", application.getAuditComment());
                statusInfo.put("applyTime", application.getApplyTime());
                statusInfo.put("auditTime", application.getAuditTime());

                // 状态描述
                String statusDesc;
                switch (application.getAuditStatus()) {
                    case 0:
                        statusDesc = "待审核";
                        break;
                    case 1:
                        statusDesc = "审核通过";
                        break;
                    case 2:
                        statusDesc = "审核拒绝";
                        break;
                    default:
                        statusDesc = "未知状态";
                }
                statusInfo.put("statusDesc", statusDesc);
            } else {
                statusInfo.put("hasApplication", false);
                statusInfo.put("statusDesc", "未申请");
            }

            return Result.success("查询申请状态成功", statusInfo);

        } catch (Exception e) {
            System.out.println("查询申请状态异常: " + e.getMessage());
            e.printStackTrace();
            return Result.error("查询申请状态失败: " + e.getMessage());
        }
    }


    // ========== 教师课程分配功能 ==========

    /**
     * 创建新课程并分配给教师
     * @param request 请求参数
     * @return 操作结果
     */
    @PostMapping("/teacher/course/create-and-assign")
    public Result createAndAssignCourse(@RequestBody CourseAssignmentRequest request) {
        System.out.println("======= 创建新课程并分配给教师 =======");
        System.out.println("请求参数: " + request);

        try {
            // 参数校验
            if (request.getUserId() == null && request.getTeacherId() == null) {
                return Result.error("用户ID或教师ID不能为空");
            }

            Integer teacherId = request.getTeacherId();

            // 如果没有传教师ID，通过用户ID查找教师ID
            if (teacherId == null && request.getUserId() != null) {
                LambdaQueryWrapper<Teachers> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(Teachers::getUserId, request.getUserId());
                Teachers teacher = teachersService.getOne(wrapper);
                if (teacher == null) {
                    return Result.error("该用户不是教师");
                }
                teacherId = teacher.getId();
            }

            // 校验必填字段
            if (!StringUtils.hasText(request.getTitle())) {
                return Result.error("课程标题不能为空");
            }
            if (request.getSubjectId() == null) {
                return Result.error("科目ID不能为空");
            }
            if (request.getPrice() == null) {
                return Result.error("课程价格不能为空");
            }

            // 创建新课程并直接分配给教师
            Courses course = new Courses();
            course.setTitle(request.getTitle());
            course.setDescription(request.getDescription());
            course.setTeacherId(teacherId); // 直接设置教师ID
            course.setSubjectId(request.getSubjectId());
            course.setPrice(request.getPrice());
            course.setOriginalPrice(request.getOriginalPrice() != null ? request.getOriginalPrice() : request.getPrice());
            course.setCoverImage(request.getCoverImage());
            course.setStatus(request.getStatus() != null ? request.getStatus() : 1); // 默认启用
            course.setCreatedAt(new Date());
            course.setUpdatedAt(new Date());

            // 保存课程
            boolean success = coursesService.save(course);

            if (success) {
                Map<String, Object> result = new HashMap<>();
                result.put("courseId", course.getId());
                result.put("teacherId", teacherId);
                return Result.success("创建课程并分配给教师成功", result);
            } else {
                return Result.error("创建课程失败");
            }

        } catch (Exception e) {
            System.out.println("创建课程并分配给教师异常: " + e.getMessage());
            e.printStackTrace();
            return Result.error("创建课程并分配给教师失败: " + e.getMessage());
        }
    }

    /**
     * 将现有课程分配给教师
     * @param request 请求参数
     * @return 操作结果
     */
    @PostMapping("/teacher/course/assign-existing")
    public Result assignExistingCourse(@RequestBody CourseAssignmentRequest request) {
        System.out.println("======= 将现有课程分配给教师 =======");
        System.out.println("请求参数: " + request);

        try {
            // 参数校验
            if (request.getUserId() == null && request.getTeacherId() == null) {
                return Result.error("用户ID或教师ID不能为空");
            }

            if (request.getCourseId() == null) {
                return Result.error("课程ID不能为空");
            }

            Integer teacherId = request.getTeacherId();

            // 如果没有传教师ID，通过用户ID查找教师ID
            if (teacherId == null && request.getUserId() != null) {
                LambdaQueryWrapper<Teachers> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(Teachers::getUserId, request.getUserId());
                Teachers teacher = teachersService.getOne(wrapper);
                if (teacher == null) {
                    return Result.error("该用户不是教师");
                }
                teacherId = teacher.getId();
            }

            // 检查课程是否存在
            Courses originalCourse = coursesService.getById(request.getCourseId());
            if (originalCourse == null) {
                return Result.error("课程不存在");
            }

            // 检查该教师是否已经有相同的课程
            LambdaQueryWrapper<Courses> checkWrapper = new LambdaQueryWrapper<>();
            checkWrapper.eq(Courses::getTeacherId, teacherId)
                       .eq(Courses::getTitle, originalCourse.getTitle())
                       .eq(Courses::getSubjectId, originalCourse.getSubjectId());
            Courses existingCourse = coursesService.getOne(checkWrapper);

            if (existingCourse != null) {
                return Result.error("该教师已经有相同的课程：" + originalCourse.getTitle());
            }

            // 为该教师创建课程副本（支持多教师授同一课程）
            Courses newCourse = new Courses();
            newCourse.setTitle(originalCourse.getTitle());
            newCourse.setDescription(originalCourse.getDescription());
            newCourse.setTeacherId(teacherId); // 分配给新教师
            newCourse.setSubjectId(originalCourse.getSubjectId());
            newCourse.setPrice(originalCourse.getPrice());
            newCourse.setOriginalPrice(originalCourse.getOriginalPrice());
            newCourse.setCoverImage(originalCourse.getCoverImage());
            newCourse.setStatus(originalCourse.getStatus());
            newCourse.setCreatedAt(new Date());
            newCourse.setUpdatedAt(new Date());

            boolean success = coursesService.save(newCourse);

            if (success) {
                Map<String, Object> result = new HashMap<>();
                result.put("courseId", newCourse.getId());
                result.put("originalCourseId", originalCourse.getId());
                result.put("teacherId", teacherId);
                result.put("courseTitle", newCourse.getTitle());
                return Result.success("课程分配给教师成功", result);
            } else {
                return Result.error("课程分配失败");
            }

        } catch (Exception e) {
            System.out.println("分配课程给教师异常: " + e.getMessage());
            e.printStackTrace();
            return Result.error("分配课程给教师失败: " + e.getMessage());
        }
    }

    /**
     * 批量分配课程给教师
     * @param request 请求参数
     * @return 操作结果
     */
    @PostMapping("/teacher/course/batch-assign")
    public Result batchAssignCourses(@RequestBody CourseAssignmentRequest request) {
        System.out.println("======= 批量分配课程给教师 =======");
        System.out.println("请求参数: " + request);

        try {
            // 参数校验
            if (request.getUserId() == null && request.getTeacherId() == null) {
                return Result.error("用户ID或教师ID不能为空");
            }

            if (request.getCourseIds() == null || request.getCourseIds().isEmpty()) {
                return Result.error("课程ID列表不能为空");
            }

            Integer teacherId = request.getTeacherId();

            // 如果没有传教师ID，通过用户ID查找教师ID
            if (teacherId == null && request.getUserId() != null) {
                LambdaQueryWrapper<Teachers> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(Teachers::getUserId, request.getUserId());
                Teachers teacher = teachersService.getOne(wrapper);
                if (teacher == null) {
                    return Result.error("该用户不是教师");
                }
                teacherId = teacher.getId();
            }

            List<String> successCourses = new ArrayList<>();
            List<String> failedCourses = new ArrayList<>();
            List<String> skippedCourses = new ArrayList<>();

            for (Integer courseId : request.getCourseIds()) {
                try {
                    // 检查课程是否存在
                    Courses originalCourse = coursesService.getById(courseId);
                    if (originalCourse == null) {
                        failedCourses.add("课程ID " + courseId + ": 课程不存在");
                        continue;
                    }

                    // 检查该教师是否已经有相同的课程
                    LambdaQueryWrapper<Courses> checkWrapper = new LambdaQueryWrapper<>();
                    checkWrapper.eq(Courses::getTeacherId, teacherId)
                               .eq(Courses::getTitle, originalCourse.getTitle())
                               .eq(Courses::getSubjectId, originalCourse.getSubjectId());
                    Courses existingCourse = coursesService.getOne(checkWrapper);

                    if (existingCourse != null) {
                        skippedCourses.add("课程《" + originalCourse.getTitle() + "》: 该教师已有相同课程");
                        continue;
                    }

                    // 为该教师创建课程副本
                    Courses newCourse = new Courses();
                    newCourse.setTitle(originalCourse.getTitle());
                    newCourse.setDescription(originalCourse.getDescription());
                    newCourse.setTeacherId(teacherId);
                    newCourse.setSubjectId(originalCourse.getSubjectId());
                    newCourse.setPrice(originalCourse.getPrice());
                    newCourse.setOriginalPrice(originalCourse.getOriginalPrice());
                    newCourse.setCoverImage(originalCourse.getCoverImage());
                    newCourse.setStatus(originalCourse.getStatus());
                    newCourse.setCreatedAt(new Date());
                    newCourse.setUpdatedAt(new Date());

                    boolean success = coursesService.save(newCourse);
                    if (success) {
                        successCourses.add("课程《" + originalCourse.getTitle() + "》");
                    } else {
                        failedCourses.add("课程《" + originalCourse.getTitle() + "》: 保存失败");
                    }

                } catch (Exception e) {
                    failedCourses.add("课程ID " + courseId + ": " + e.getMessage());
                }
            }

            // 组装返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("teacherId", teacherId);
            result.put("successCount", successCourses.size());
            result.put("failedCount", failedCourses.size());
            result.put("skippedCount", skippedCourses.size());
            result.put("successCourses", successCourses);
            result.put("failedCourses", failedCourses);
            result.put("skippedCourses", skippedCourses);

            if (failedCourses.isEmpty() && skippedCourses.isEmpty()) {
                return Result.success("批量分配课程成功", result);
            } else if (successCourses.isEmpty()) {
                return Result.error("批量分配课程全部失败"+result);
            } else {
                return Result.success("批量分配课程部分成功", result);
            }

        } catch (Exception e) {
            System.out.println("批量分配课程异常: " + e.getMessage());
            e.printStackTrace();
            return Result.error("批量分配课程失败: " + e.getMessage());
        }
    }

    /**
     * 查询教师已分配的课程
     * @param userIdStr 用户ID字符串
     * @param teacherIdStr 教师ID字符串
     * @param page 页码
     * @param pageSize 每页大小
     * @param keyword 关键词
     * @return 课程列表
     */
    @GetMapping("/teacher/course/assigned-list")
    public Result getAssignedCourses(
            @RequestParam(value = "userId", required = false) String userIdStr,
            @RequestParam(value = "teacherId", required = false) String teacherIdStr,
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(value = "keyword", required = false) String keyword) {

        System.out.println("======= 查询教师已分配的课程 =======");
        System.out.println("用户ID: " + userIdStr + ", 教师ID: " + teacherIdStr + ", 页码: " + page + ", 每页大小: " + pageSize + ", 关键词: " + keyword);

        try {
            // 参数转换和校验
            Integer userId = parseIntegerParam(userIdStr);
            Integer teacherId = parseIntegerParam(teacherIdStr);

            if (userId == null && teacherId == null) {
                return Result.error("用户ID或教师ID不能为空");
            }

            Integer finalTeacherId = teacherId;

            // 如果没有传教师ID，通过用户ID查找教师ID
            if (finalTeacherId == null && userId != null) {
                LambdaQueryWrapper<Teachers> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(Teachers::getUserId, userId);
                Teachers teacher = teachersService.getOne(wrapper);
                if (teacher == null) {
                    return Result.error("该用户不是教师");
                }
                finalTeacherId = teacher.getId();
            }

            // 构建查询条件
            Page<Courses> pageInfo = new Page<>(page, pageSize);
            LambdaQueryWrapper<Courses> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Courses::getTeacherId, finalTeacherId);

            // 关键词搜索
            if (StringUtils.hasText(keyword)) {
                wrapper.and(w -> w.like(Courses::getTitle, keyword)
                                .or()
                                .like(Courses::getDescription, keyword));
            }

            wrapper.orderByDesc(Courses::getCreatedAt);

            // 执行查询
            Page<Courses> coursePage = coursesService.page(pageInfo, wrapper);

            // 组装返回数据
            List<Map<String, Object>> resultList = new ArrayList<>();
            for (Courses course : coursePage.getRecords()) {
                Map<String, Object> courseInfo = new HashMap<>();
                courseInfo.put("id", course.getId());
                courseInfo.put("title", course.getTitle());
                courseInfo.put("description", course.getDescription());
                courseInfo.put("teacherId", course.getTeacherId());
                courseInfo.put("subjectId", course.getSubjectId());
                courseInfo.put("price", course.getPrice());
                courseInfo.put("originalPrice", course.getOriginalPrice());
                courseInfo.put("coverImage", course.getCoverImage());
                courseInfo.put("status", course.getStatus());
                courseInfo.put("createdAt", course.getCreatedAt());
                courseInfo.put("updatedAt", course.getUpdatedAt());

                // 查询科目名称
                if (course.getSubjectId() != null) {
                    Subjects subject = subjectsService.getById(course.getSubjectId());
                    courseInfo.put("subjectName", subject != null ? subject.getName() : "未知科目");
                }

                resultList.add(courseInfo);
            }

            // 返回结果，包含分页信息
            Map<String, Object> result = new HashMap<>();
            result.put("records", resultList);
            result.put("total", coursePage.getTotal());
            result.put("pages", coursePage.getPages());
            result.put("current", coursePage.getCurrent());
            result.put("size", coursePage.getSize());

            return Result.success("查询教师已分配课程成功", result);

        } catch (Exception e) {
            System.out.println("查询教师已分配课程异常: " + e.getMessage());
            e.printStackTrace();
            return Result.error("查询教师已分配课程失败: " + e.getMessage());
        }
    }

    /**
     * 查询教师可分配的课程列表（排除已分配给该教师的课程）
     * @param userIdStr 用户ID字符串
     * @param teacherIdStr 教师ID字符串
     * @param page 页码
     * @param pageSize 每页大小
     * @param keyword 关键词
     * @param subjectIdStr 科目ID字符串
     * @return 课程列表
     */
    @GetMapping("/teacher/course/available-list")
    public Result getAvailableCourses(
            @RequestParam(value = "userId", required = false) String userIdStr,
            @RequestParam(value = "teacherId", required = false) String teacherIdStr,
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(value = "keyword", required = false) String keyword,
            @RequestParam(value = "subjectId", required = false) String subjectIdStr) {

        System.out.println("======= 查询教师可分配的课程列表 =======");
        System.out.println("用户ID: " + userIdStr + ", 教师ID: " + teacherIdStr + ", 页码: " + page + ", 每页大小: " + pageSize + ", 关键词: " + keyword + ", 科目ID: " + subjectIdStr);

        try {
            // 参数转换和校验
            Integer userId = parseIntegerParam(userIdStr);
            Integer teacherId = parseIntegerParam(teacherIdStr);
            Integer subjectId = parseIntegerParam(subjectIdStr);

            if (userId == null && teacherId == null) {
                return Result.error("用户ID或教师ID不能为空");
            }

            Integer finalTeacherId = teacherId;

            // 如果没有传教师ID，通过用户ID查找教师ID
            if (finalTeacherId == null && userId != null) {
                LambdaQueryWrapper<Teachers> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(Teachers::getUserId, userId);
                Teachers teacher = teachersService.getOne(wrapper);
                if (teacher == null) {
                    return Result.error("该用户不是教师");
                }
                finalTeacherId = teacher.getId();
            }

            if (keyword==null){
                keyword = "";
            }
            // 构建查询条件 - 查询所有课程，但排除该教师已有的相同课程
            Page<Courses> pageInfo = new Page<>(page, pageSize);
            LambdaQueryWrapper<Courses> wrapper = new LambdaQueryWrapper<>();

            // 查询所有启用的课程
            wrapper.eq(Courses::getStatus, 1);

            // 科目过滤
            if (subjectId != null) {
                wrapper.eq(Courses::getSubjectId, subjectId);
            }

            // 关键词搜索
            if (StringUtils.hasText(keyword)) {
                String finalKeyword = keyword;
                wrapper.and(w -> w.like(Courses::getTitle, finalKeyword)
                                .or()
                                .like(Courses::getDescription, finalKeyword));
            }

            wrapper.orderByDesc(Courses::getCreatedAt);

            // 执行查询
            Page<Courses> coursePage = coursesService.page(pageInfo, wrapper);

            // 过滤掉该教师已有的相同课程
            List<Map<String, Object>> resultList = new ArrayList<>();
            for (Courses course : coursePage.getRecords()) {
                // 检查该教师是否已经有相同的课程
                LambdaQueryWrapper<Courses> checkWrapper = new LambdaQueryWrapper<>();
                checkWrapper.eq(Courses::getTeacherId, finalTeacherId)
                           .eq(Courses::getTitle, course.getTitle())
                           .eq(Courses::getSubjectId, course.getSubjectId());
                Courses existingCourse = coursesService.getOne(checkWrapper);

                // 如果该教师没有相同的课程，则可以分配
                if (existingCourse == null) {
                    Map<String, Object> courseInfo = new HashMap<>();
                    courseInfo.put("id", course.getId());
                    courseInfo.put("title", course.getTitle());
                    courseInfo.put("description", course.getDescription());
                    courseInfo.put("teacherId", course.getTeacherId());
                    courseInfo.put("subjectId", course.getSubjectId());
                    courseInfo.put("price", course.getPrice());
                    courseInfo.put("originalPrice", course.getOriginalPrice());
                    courseInfo.put("coverImage", course.getCoverImage());
                    courseInfo.put("status", course.getStatus());
                    courseInfo.put("createdAt", course.getCreatedAt());

                    // 查询科目名称
                    if (course.getSubjectId() != null) {
                        Subjects subject = subjectsService.getById(course.getSubjectId());
                        courseInfo.put("subjectName", subject != null ? subject.getName() : "未知科目");
                    }

                    // 查询原教师信息
                    if (course.getTeacherId() != null) {
                        Teachers teacher = teachersService.getById(course.getTeacherId());
                        courseInfo.put("originalTeacherName", teacher != null ? teacher.getName() : "未知教师");
                    }

                    resultList.add(courseInfo);
                }
            }

            // 返回结果，包含分页信息
            Map<String, Object> result = new HashMap<>();
            result.put("records", resultList);
            result.put("total", (long) resultList.size()); // 过滤后的总数
            result.put("pages", resultList.size() > 0 ? (resultList.size() + pageSize - 1) / pageSize : 0);
            result.put("current", page);
            result.put("size", pageSize);

            return Result.success("查询可分配课程列表成功", result);

        } catch (Exception e) {
            System.out.println("查询可分配课程列表异常: " + e.getMessage());
            e.printStackTrace();
            return Result.error("查询可分配课程列表失败: " + e.getMessage());
        }
    }

    /**
     * 取消教师课程分配
     * @param request 请求参数
     * @return 操作结果
     */
    @PostMapping("/teacher/course/unassign")
    public Result unassignCourse(@RequestBody CourseAssignmentRequest request) {
        System.out.println("======= 取消教师课程分配 =======");
        System.out.println("请求参数: " + request);

        try {
            // 参数校验
            if (request.getCourseId() == null) {
                return Result.error("课程ID不能为空");
            }

            if (request.getUserId() == null && request.getTeacherId() == null) {
                return Result.error("用户ID或教师ID不能为空");
            }

            Integer teacherId = request.getTeacherId();

            // 如果没有传教师ID，通过用户ID查找教师ID
            if (teacherId == null && request.getUserId() != null) {
                LambdaQueryWrapper<Teachers> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(Teachers::getUserId, request.getUserId());
                Teachers teacher = teachersService.getOne(wrapper);
                if (teacher == null) {
                    return Result.error("该用户不是教师");
                }
                teacherId = teacher.getId();
            }

            // 检查课程是否存在且属于该教师
            Courses course = coursesService.getById(request.getCourseId());
            if (course == null) {
                return Result.error("课程不存在");
            }

            // 检查课程是否属于该教师
            if (!teacherId.equals(course.getTeacherId())) {
                return Result.error("该课程不属于此教师");
            }

            // 删除课程（取消分配）
            boolean success = coursesService.removeById(request.getCourseId());

            if (success) {
                Map<String, Object> result = new HashMap<>();
                result.put("courseId", course.getId());
                result.put("courseTitle", course.getTitle());
                result.put("teacherId", teacherId);
                return Result.success("取消课程分配成功", result);
            } else {
                return Result.error("取消课程分配失败");
            }

        } catch (Exception e) {
            System.out.println("取消课程分配异常: " + e.getMessage());
            e.printStackTrace();
            return Result.error("取消课程分配失败: " + e.getMessage());
        }
    }

    /**
     * 查询课程的授课教师列表
     * @param courseId 课程ID
     * @return 教师列表
     */
    @GetMapping("/teacher/course/teachers")
    public Result getCourseTeachers(@RequestParam("courseId") Integer courseId) {
        System.out.println("======= 查询课程的授课教师列表 =======");
        System.out.println("课程ID: " + courseId);

        try {
            // 参数校验
            if (courseId == null) {
                return Result.error("课程ID不能为空");
            }

            // 查询所有同名同科目的课程
            LambdaQueryWrapper<Courses> courseWrapper = new LambdaQueryWrapper<>();
            courseWrapper.eq(Courses::getId, courseId);
            Courses baseCourse = coursesService.getOne(courseWrapper);

            if (baseCourse == null) {
                return Result.error("课程不存在");
            }

            // 查询所有同名同科目的课程及其教师
            LambdaQueryWrapper<Courses> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Courses::getTitle, baseCourse.getTitle())
                   .eq(Courses::getSubjectId, baseCourse.getSubjectId())
                   .isNotNull(Courses::getTeacherId);

            List<Courses> sameCourses = coursesService.list(wrapper);

            List<Map<String, Object>> teachers = new ArrayList<>();
            for (Courses course : sameCourses) {
                if (course.getTeacherId() != null) {
                    Teachers teacher = teachersService.getById(course.getTeacherId());
                    if (teacher != null) {
                        Map<String, Object> teacherInfo = new HashMap<>();
                        teacherInfo.put("teacherId", teacher.getId());
                        teacherInfo.put("teacherName", teacher.getName());
                        teacherInfo.put("teachingAge", teacher.getTeachingAge());
                        teacherInfo.put("introduction", teacher.getIntroduction());
                        teacherInfo.put("courseId", course.getId());
                        teacherInfo.put("assignTime", course.getCreatedAt());
                        teacherInfo.put("status", course.getStatus());
                        teachers.add(teacherInfo);
                    }
                }
            }

            Map<String, Object> result = new HashMap<>();
            result.put("courseId", courseId);
            result.put("courseTitle", baseCourse.getTitle());
            result.put("teachers", teachers);
            result.put("teacherCount", teachers.size());

            return Result.success("查询课程授课教师列表成功", result);

        } catch (Exception e) {
            System.out.println("查询课程授课教师列表异常: " + e.getMessage());
            e.printStackTrace();
            return Result.error("查询课程授课教师列表失败: " + e.getMessage());
        }
    }

}
